package bargain.server.service.impl;

import bargain.enitity.Account;
import bargain.enitity.FreezeAssets;
import bargain.server.dao.AccountDao;
import bargain.server.dao.FreezeAssetsDao;
import bargain.service.AService;
import bargain.service.BService;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.dromara.hmily.annotation.HmilyTCC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @ClassName AServiceImpl
 * @Description
 * @Author Jingxiao.Ye
 * @Date 2022/1/4 下午9:46
 * @Version V1.0
 * @Since JDK 11
 */
@DubboService
@Service
public class AServiceImpl implements AService {

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private FreezeAssetsDao freezeAssetsDao;

    @DubboReference
    private BService bService;

    @Override
    @HmilyTCC(confirmMethod = "successTransferAccount",cancelMethod = "failTransferAccount")
    public void transferAccount(long tranId,long accountId,long accountIdB, BigDecimal dollar, BigDecimal rmb) {
        Account account = new Account();
        account.setDollar(dollar);
        account.setId(accountId);
        int i = accountDao.reduceDollar(account);
        if(i > 0){
            FreezeAssets freezeAssets = new FreezeAssets();
            freezeAssets.setCreateTime(System.currentTimeMillis());
            freezeAssets.setDollar(dollar);
            freezeAssets.setRmb(BigDecimal.valueOf(0));
            freezeAssets.setAccountId(accountId);
            freezeAssets.setId(tranId);
            freezeAssetsDao.save(freezeAssets);
            bService.transferAccount(tranId,accountIdB,dollar,rmb);
        }else {
            throw new RuntimeException("余额不足");
        }
    }

    @Transactional
    public void successTransferAccount(long tranId,long accountId,long accountIdB, BigDecimal dollar, BigDecimal rmb){

        int del = freezeAssetsDao.del(tranId);
        if(del > 0){
            Account account = new Account();
            account.setRmb(rmb);
            account.setId(accountId);
            accountDao.addRmb(account);
        }
    }

    @Transactional
    public void failTransferAccount(long tranId,long accountId,long accountIdB, BigDecimal dollar, BigDecimal rmb){
        int del = freezeAssetsDao.del(tranId);
        if(del > 0){
            Account account = new Account();
            account.setDollar(dollar);
            account.setId(accountId);
            accountDao.addDollar(account);
        }
    }
}
